<?php
declare (strict_types = 1);

namespace app\cli\controller;

use app\common\model\mysql\Goods;
use Es\MyElasticsearch;
use think\Request;

class Es
{
    /**
     * 显示资源列表
     *创建商品索引并导入全部商品
     * 切换到public目录下 php index.php /cli/Es/createAllGoodsDocs
     * @return \think\Response
     */
    public $index = 'goods_index';//库名
    public $type = 'goods_type';//表明
    public function createAllGoodsDocs()
    {
        try {
            //实例化ES工具类
            $es = new MyElasticsearch();
            //创建索引
            if($es->existsIndex($this->index)) $es->delete_index($this->index);
            $es->create_index($this->index);

            $i = 0;
            while (true){
                //查询商品数量 每次处理100条
                $goods = Goods::with('category')->field('id,goods_name,goods_desc,goods_price,goods_logo,cate_id')->limit($i,1000)->select()->toArray();
                dump($goods);
                if(empty($goods)){
                    //查询结果为空,则停止
                    break;
                }
                //添加文档
                foreach($goods as $v){
                    unset($v['cate_id']);
                    $es->add_doc($v['id'],$v,$this->index,$this->type);
                }
                $i +=1000;

            }
            die('success');

        }catch (\Exception $e){
            $msg = $e->getMessage();
            die($msg);
        }
    }
    public function test()
    {
        echo 123;
    }


}
